<!DOCTYPE html>
<html>
<head>
  <title>添加订单 - 订单管理系统</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    :root {
      --primary-color: #4361ee;
      --secondary-color: #3f37c9;
      --success-color: #4cc9f0;
    }
    
    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      min-height: 100vh;
      max-width: 1440px;
      margin: 0 auto;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .form-card {
      width: 100%;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.1);
      background: white;
      margin: 20px auto;
      overflow: hidden;
    }
    
    .form-header {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      padding: 25px;
      text-align: center;
    }
    
    .form-body {
      padding: 30px;
    }
    
    .form-section {
      margin-bottom: 30px;
      padding: 20px;
      border-radius: 10px;
      background-color: #f8f9fa;
      border-left: 4px solid var(--primary-color);
    }
    
    .form-section h5 {
      color: var(--primary-color);
      margin-bottom: 20px;
      font-weight: 600;
    }
    
    .form-control, .form-select {
      height: 46px;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.15);
      outline: none;
    }
    
    .input-group-text {
      background: #e9ecef;
      border: 1px solid #dee2e6;
      border-radius: 8px 0 0 8px;
      color: #495057;
      min-width: 45px;
      text-align: center;
    }
    
    .btn-primary {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      border: none;
      color: white;
      padding: 12px 20px;
      font-weight: 600;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
    }
    
    .btn-primary:hover {
      background: linear-gradient(120deg, var(--secondary-color), var(--primary-color));
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
    }
    
    .btn-success {
      background: linear-gradient(120deg, #28a745, #20c997);
      border: none;
      color: white;
      padding: 12px 20px;
      font-weight: 600;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }
    
    .btn-success:hover {
      background: linear-gradient(120deg, #20c997, #28a745);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
    }
    
    .btn-danger {
      background: linear-gradient(120deg, #dc3545, #e74c3c);
      border: none;
      color: white;
      padding: 12px 20px;
      font-weight: 600;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
    }
    
    .btn-danger:hover {
      background: linear-gradient(120deg, #e74c3c, #dc3545);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4);
    }
    
    .btn-secondary {
      background: linear-gradient(120deg, #6c757d, #495057);
      border: none;
      color: white;
      padding: 12px 20px;
      font-weight: 600;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }
    
    .btn-secondary:hover {
      background: linear-gradient(120deg, #495057, #6c757d);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
    }
    
    .top-nav {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      padding: 15px 0;
      margin-bottom: 25px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .nav-link {
      color: rgba(255, 255, 255, 0.8) !important;
      font-weight: 500;
      transition: all 0.3s;
      border-radius: 5px;
      margin: 0 5px;
    }
    
    .nav-link:hover, .nav-link.active {
      color: white !important;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .product-item {
      background: white;
      border-radius: 10px;
      padding: 20px;
      margin-bottom: 15px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      border: 1px solid #e9ecef;
      transition: all 0.3s;
    }
    
    .product-item:hover {
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      transform: translateY(-2px);
    }
    
    .remove-product {
      cursor: pointer;
      color: #dc3545;
      transition: all 0.3s;
    }
    
    .remove-product:hover {
      color: #bd2130;
      transform: scale(1.1);
    }
    
    .search-product-input {
      border-radius: 20px;
    }
    
    .product-search-results {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      margin-top: 5px;
      display: none;
    }
    
    .product-search-item {
      padding: 10px 15px;
      border-bottom: 1px solid #eee;
      cursor: pointer;
      transition: all 0.2s;
    }
    
    .product-search-item:hover {
      background-color: #f8f9fa;
    }
    
    .product-search-item:last-child {
      border-bottom: none;
    }
    
    .alert {
      border-radius: 8px;
    }
    
    .footer-buttons {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #e9ecef;
    }
  </style>
</head>
<body>
  <!-- 顶部导航 -->
  <div class="top-nav">
    <div class="container">
      <nav class="navbar navbar-expand navbar-dark">
        <div class="navbar-nav">
          <a class="nav-link" href="/"><i class="fas fa-home me-1"></i> 系统首页</a>
          <a class="nav-link" href="/orders"><i class="fas fa-list me-1"></i> 订单管理</a>
          <a class="nav-link" href="/customers"><i class="fas fa-users me-1"></i> 客户管理</a>
          {% if current_user and current_user.role == "root" %}
          <a class="nav-link" href="/users"><i class="fas fa-user-cog me-1"></i> 用户管理</a>
          {% endif %}
        </div>
      </nav>
    </div>
  </div>

  <div class="form-card">
    <div class="form-header">
      <h3><i class="fas fa-plus-circle me-2"></i>添加订单</h3>
      <p>订单管理系统</p>
    </div>
    <div class="form-body">
      {% if error %}
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <i class="fas fa-exclamation-circle me-2"></i>{{ error }}
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      {% endif %}
      
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% for category, message in messages %}
            <div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
              <i class="fas fa-{{ 'exclamation-circle' if category == 'error' else 'check-circle' }} me-2"></i>{{ message }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
          {% endfor %}
        {% endif %}
      {% endwith %}
      
      <form method="POST" id="addOrderForm">
        <div class="row">
          <div class="col-md-6">
            <div class="form-section">
              <h5><i class="fas fa-info-circle me-2"></i>订单信息</h5>
              <div class="mb-3">
                <label for="order_id" class="form-label">订单ID *</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                  <input type="text" class="form-control" id="order_id" name="order_id" required placeholder="请输入订单ID">
                </div>
              </div>
              <div class="mb-3">
                <label for="source" class="form-label">来源站点 *</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-globe"></i></span>
                  <select class="form-select" id="source" name="source" required>
                    <option value="">请选择来源站点</option>
                    {% for site in SITES %}
                      <option value="{{ site.user }}">{{ site.user }} ({{ site.domain }})</option>
                    {% endfor %}
                  </select>
                </div>
              </div>
              <div class="mb-3">
                <label for="status" class="form-label">订单状态</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-tasks"></i></span>
                  <select class="form-select" id="status" name="status">
                    <option value="processing">待处理</option>
                    <option value="completed">已完成</option>
                    <option value="cancelled">已取消</option>
                    <option value="refunded">已退款</option>
                    <option value="on-hold">发货中</option>
                    <option value="failed">被拒收</option>
                  </select>
                </div>
              </div>
              <div class="mb-3">
                <label for="total" class="form-label">订单总额 *</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span>
                  <input type="number" class="form-control" id="total" name="total" step="0.01" required placeholder="请输入订单总额">
                  <span class="input-group-text" id="currencySymbol">USD</span>
                </div>
              </div>
              <div class="mb-3">
                <label for="item_count" class="form-label">商品数量</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-boxes"></i></span>
                  <input type="number" class="form-control" id="item_count" name="item_count" value="0" placeholder="商品总数量">
                </div>
              </div>
              <!-- 运费信息 -->
              <div class="mb-3">
                <label class="form-label">运费信息</label>
                <div class="row">
                  <div class="col-md-7 mb-2">
                    <div class="input-group">
                      <span class="input-group-text"><i class="fas fa-truck"></i></span>
                      <select class="form-select" id="shipping_method" name="shipping_method">
                        <option value="">请选择运费方式</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-5 mb-2">
                    <div class="input-group">
                      <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span>
                      <input type="number" class="form-control" id="shipping_total" name="shipping_total" step="0.01" value="0" placeholder="运费" readonly>
                      <span class="input-group-text" id="shippingCurrencySymbol">USD</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="col-md-6">
            <div class="form-section">
              <h5><i class="fas fa-user me-2"></i>客户信息</h5>
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="customer_first_name" class="form-label">名 (First Name)</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                    <input type="text" class="form-control" id="customer_first_name" name="customer_first_name" placeholder="客户名">
                  </div>
                </div>
                <div class="col-md-6 mb-3">
                  <label for="customer_last_name" class="form-label">姓 (Last Name)</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                    <input type="text" class="form-control" id="customer_last_name" name="customer_last_name" placeholder="客户姓">
                  </div>
                </div>
              </div>
              
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="customer_email" class="form-label">邮箱</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                    <input type="email" class="form-control" id="customer_email" name="customer_email" placeholder="客户邮箱">
                  </div>
                </div>
                <div class="col-md-6 mb-3">
                  <label for="customer_phone" class="form-label">电话</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-phone"></i></span>
                    <input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="客户电话">
                  </div>
                </div>
              </div>
              
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="customer_country" class="form-label">国家</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-flag"></i></span>
                    <select class="form-select" id="customer_country" name="customer_country">
                      <option value="">请选择国家</option>
                      {% for country in unique_countries %}
                        <option value="{{ country }}">{{ country | country_name }}</option>
                      {% endfor %}
                    </select>
                  </div>
                </div>
                <div class="col-md-6 mb-3">
                  <label for="customer_city" class="form-label">城市</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-city"></i></span>
                    <input type="text" class="form-control" id="customer_city" name="customer_city" placeholder="城市">
                  </div>
                </div>
              </div>
              
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label for="customer_state" class="form-label">州/省</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
                    <input type="text" class="form-control" id="customer_state" name="customer_state" placeholder="州/省">
                  </div>
                </div>
                <div class="col-md-6 mb-3">
                  <label for="customer_postcode" class="form-label">邮编</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-mail-bulk"></i></span>
                    <input type="text" class="form-control" id="customer_postcode" name="customer_postcode" placeholder="邮政编码">
                  </div>
                </div>
              </div>
              
              <div class="mb-3">
                <label for="customer_address" class="form-label">地址</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-home"></i></span>
                  <textarea class="form-control" id="customer_address" name="customer_address" rows="2" placeholder="详细地址"></textarea>
                </div>
              </div>
              
              <div class="mb-3">
                <label for="customer_address_2" class="form-label">第二地址</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-building"></i></span>
                  <textarea class="form-control" id="customer_address_2" name="customer_address_2" rows="2" placeholder="第二地址"></textarea>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="form-section">
          <h5><i class="fas fa-box me-2"></i>商品详情</h5>
          <div class="mb-3">
            <label class="form-label">添加商品</label>
            <div class="input-group mb-3">
              <span class="input-group-text"><i class="fas fa-search"></i></span>
              <input type="text" class="form-control search-product-input" id="searchProduct" placeholder="搜索WooCommerce商品...">
              <span class="input-group-text text-muted small">输入关键词实时搜索</span>
            </div>
            <div class="product-search-results" id="productSearchResults"></div>
          </div>
          
          <div class="mb-3">
            <button type="button" class="btn btn-success mb-3" id="addManualProductBtn">
              <i class="fas fa-plus me-2"></i>手动添加商品
            </button>
            <div id="productsContainer">
              <!-- 商品项将通过JavaScript动态添加 -->
            </div>
          </div>
          
          <!-- 隐藏的商品详情JSON字段 -->
          <textarea class="form-control d-none" id="item_details" name="item_details" rows="5"></textarea>
        </div>
        
        <div class="footer-buttons">
          <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <a href="/orders" class="btn btn-secondary">
              <i class="fas fa-times me-2"></i>取消
            </a>
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-save me-2"></i>添加订单
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- 隐藏的站点货币信息 -->
  <script id="siteCurrenciesData" type="application/json">
    {
      {% for site in SITES %}
        "{{ site.user }}": "{{ site.currency|default('USD') }}"{% if not loop.last %},{% endif %}
      {% endfor %}
    }
  </script>
  
  <!-- 隐藏的站点运费方法信息 -->
  <script id="siteShippingMethodsData" type="application/json">
    {
      {% for site in SITES %}
        "{{ site.user }}": {{ site.shipping_methods | tojson }}{% if not loop.last %},{% endif %}
      {% endfor %}
    }
  </script>
  
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // 商品数据数组
    let products = [];
    
    // 站点货币映射 - 从后端传递的SITES配置中提取
    const siteCurrencies = JSON.parse(document.getElementById('siteCurrenciesData').textContent);
    
    // 站点运费方法映射
    const siteShippingMethods = JSON.parse(document.getElementById('siteShippingMethodsData').textContent);
    
    // 当来源站点改变时，更新货币符号和运费方式
    document.getElementById('source').addEventListener('change', function() {
      const source = this.value;
      const currencySymbol = document.getElementById('currencySymbol');
      const shippingCurrencySymbol = document.getElementById('shippingCurrencySymbol');
      
      // 根据选择的来源站点更新货币符号
      let currency = 'USD'; // 默认货币
      if (source && siteCurrencies[source]) {
        currency = siteCurrencies[source];
      }
      currencySymbol.textContent = currency;
      shippingCurrencySymbol.textContent = currency; // 运费货币符号与订单总额保持一致
      
      // 更新运费方式下拉框
      updateShippingMethods(source);
    });
    
    // 更新运费方式下拉框
    function updateShippingMethods(source) {
      const shippingMethodSelect = document.getElementById('shipping_method');
      const shippingTotalInput = document.getElementById('shipping_total');
      const shippingCurrencySymbol = document.getElementById('shippingCurrencySymbol');
      
      // 清空现有选项
      shippingMethodSelect.innerHTML = '<option value="">请选择运费方式</option>';
      
      // 如果有选中的站点，添加对应的运费方式
      if (source && siteShippingMethods[source]) {
        // 获取站点货币
        const currency = siteCurrencies[source] || 'USD';
        
        siteShippingMethods[source].forEach(method => {
          const option = document.createElement('option');
          option.value = method.cost;
          option.textContent = `${method.name} (${method.cost} ${currency})`;
          option.dataset.methodName = method.name;
          option.dataset.methodId = method.id;
          shippingMethodSelect.appendChild(option);
        });
      }
      
      // 重置运费总额
      shippingTotalInput.value = '0.00';
      
      // 更新订单总额
      updateOrderTotal();
    }
    
    // 当运费方式改变时，更新运费总额
    document.getElementById('shipping_method').addEventListener('change', function() {
      const shippingTotalInput = document.getElementById('shipping_total');
      shippingTotalInput.value = this.value || '0.00';
      
      // 更新订单总额
      updateOrderTotal();
    });
    
    // 更新订单总额（商品总额 + 运费总额）
    function updateOrderTotal() {
      // 计算商品总额
      const productsTotal = products.reduce((sum, product) => sum + (parseFloat(product.total) || 0), 0);
      
      // 获取运费总额
      const shippingTotal = parseFloat(document.getElementById('shipping_total').value) || 0;
      
      // 计算订单总额
      const orderTotal = productsTotal + shippingTotal;
      
      // 更新订单总额输入框
      document.getElementById('total').value = orderTotal.toFixed(2);
      
      // 更新商品数量
      const itemCount = products.reduce((sum, product) => sum + (parseInt(product.quantity) || 0), 0);
      document.getElementById('item_count').value = itemCount;
    }
    
    // 添加手动商品
    document.getElementById('addManualProductBtn').addEventListener('click', function() {
      addProductItem({
        id: '',
        name: '',
        sku: '',
        price: 0,
        quantity: 1,
        total: 0,
        attributes: []
      });
    });
    
    // 移除搜索按钮的点击事件监听器，因为我们使用实时搜索
    // document.getElementById('searchProductBtn').addEventListener('click', function() {
    //   searchProducts();
    // });
    
    // 移除回车搜索事件监听器，因为我们将使用实时搜索
    // document.getElementById('searchProduct').addEventListener('keypress', function(e) {
    //   if (e.key === 'Enter') {
    //     searchProducts();
    //   }
    // });
    
    // 添加防抖函数
    function debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    }
    
    // 实时搜索商品（防抖版本）
    const debouncedSearchProducts = debounce(function() {
      const searchTerm = document.getElementById('searchProduct').value.trim();
      // 使用页面顶部的来源站点而不是商品详情部分的站点选择
      const site = document.getElementById('source').value;
      const resultsContainer = document.getElementById('productSearchResults');
      
      // 如果搜索词为空，隐藏搜索结果
      if (!searchTerm) {
        resultsContainer.style.display = 'none';
        return;
      }
      
      if (!site) {
        // 如果没有选择站点，不进行搜索
        return;
      }
      
      // 显示加载状态
      resultsContainer.innerHTML = '<div class="p-3 text-center"><div class="spinner-border text-primary" role="status"></div></div>';
      resultsContainer.style.display = 'block';
      
      // 发送API请求
      fetch(`/api/woocommerce/products?site=${encodeURIComponent(site)}&search=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            displaySearchResults(data.products);
          } else {
            resultsContainer.innerHTML = `<div class="p-3 text-danger">搜索失败: ${data.error}</div>`;
          }
        })
        .catch(error => {
          resultsContainer.innerHTML = `<div class="p-3 text-danger">搜索出错: ${error.message}</div>`;
        });
    }, 300); // 300ms防抖延迟
    
    // 添加实时搜索事件监听器 - 使用input事件实现onkey效果
    document.getElementById('searchProduct').addEventListener('input', function(e) {
      debouncedSearchProducts();
    });
    
    // 也监听keyup事件以确保兼容性
    document.getElementById('searchProduct').addEventListener('keyup', function(e) {
      debouncedSearchProducts();
    });
    
    // 隐藏搜索按钮，因为我们使用实时搜索
    document.getElementById('searchProductBtn').style.display = 'none';
    
    // 修改搜索商品函数，用于手动触发搜索（如果需要）
    function searchProducts() {
      debouncedSearchProducts();
    }
    
    // 显示搜索结果
    function displaySearchResults(products) {
      const resultsContainer = document.getElementById('productSearchResults');
      
      if (products.length === 0) {
        resultsContainer.innerHTML = '<div class="p-3 text-muted">未找到相关商品</div>';
        return;
      }
      
      let html = '';
      products.forEach(product => {
        // 检查是否为可变商品
        const isVariable = product.variations && product.variations.length > 0;
        
        html += `
          <div class="product-search-item" onclick="selectProduct(${JSON.stringify(product).replace(/"/g, '&quot;')})">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <strong>${product.name}</strong>
                <div class="small text-muted">SKU: ${product.sku || 'N/A'} | 价格: $${product.price || '0.00'}</div>
                ${isVariable ? `<div class="small text-warning">可变商品 (${product.variations.length} 个变体)</div>` : ''}
              </div>
              <div class="text-primary">
                <i class="fas fa-plus-circle"></i>
              </div>
            </div>
          </div>
        `;
      });
      
      resultsContainer.innerHTML = html;
    }
    
    // 选择商品
    function selectProduct(product) {
      // 隐藏搜索结果
      document.getElementById('productSearchResults').style.display = 'none';
      document.getElementById('searchProduct').value = '';
      
      // 检查是否为可变商品
      if (product.variations && product.variations.length > 0) {
        // 对于可变商品，我们需要获取变体详情
        fetchProductVariations(product);
      } else {
        // 添加普通商品到列表
        // 处理商品名称，确保不为undefined
        const productName = product.name || '未命名商品';
        
        // 处理商品属性，确保属性值正确显示
        let processedAttributes = [];
        if (product.attributes && product.attributes.length > 0) {
          processedAttributes = product.attributes.map(attr => {
            // 对于主商品，如果option和value都为空，尝试从options中获取第一个值
            let attrValue = attr.value || attr.option || '';
            if (!attrValue && attr.options && attr.options.length > 0) {
              attrValue = attr.options[0];
            }
            return {
              name: attr.name || '',
              value: attrValue
            };
          });
        }
        
        addProductItem({
          id: product.id || '',
          name: productName,
          sku: product.sku || '',
          price: parseFloat(product.price) || 0,
          quantity: 1,
          total: parseFloat(product.price) || 0,
          attributes: processedAttributes
        });
      }
    }
    
    // 获取商品变体详情
    function fetchProductVariations(product) {
      const site = document.getElementById('source').value;
      
      if (!site) {
        alert('请选择来源站点');
        return;
      }
      
      // 显示加载状态
      const resultsContainer = document.getElementById('productSearchResults');
      resultsContainer.innerHTML = '<div class="p-3 text-center"><div class="spinner-border text-primary" role="status"></div><div class="mt-2">正在加载商品变体...</div></div>';
      resultsContainer.style.display = 'block';
      
      // 获取所有变体的详细信息
      const variationIds = product.variations;
      const variationPromises = variationIds.map(variationId => {
        return fetch(`/api/woocommerce/products/${product.id}/variations/${variationId}?site=${encodeURIComponent(site)}`)
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              return data.variation;
            }
            return null;
          })
          .catch(() => null);
      });
      
      Promise.all(variationPromises)
        .then(variations => {
          // 过滤掉获取失败的变体
          const validVariations = variations.filter(v => v !== null);
          
          if (validVariations.length > 0) {
            // 显示变体选择界面
            displayVariationSelection(product, validVariations);
          } else {
            // 如果无法获取变体信息，添加原始商品
            addProductItem({
              id: product.id,
              name: product.name,
              sku: product.sku,
              price: parseFloat(product.price) || 0,
              quantity: 1,
              total: parseFloat(product.price) || 0,
              attributes: product.attributes || []
            });
            resultsContainer.style.display = 'none';
          }
        })
        .catch(error => {
          console.error('获取变体信息失败:', error);
          // 如果获取变体信息失败，添加原始商品
          addProductItem({
            id: product.id,
            name: product.name,
            sku: product.sku,
            price: parseFloat(product.price) || 0,
            quantity: 1,
            total: parseFloat(product.price) || 0,
            attributes: product.attributes || []
          });
          resultsContainer.style.display = 'none';
        });
    }
    
    // 显示变体选择界面
    function displayVariationSelection(product, variations) {
      const resultsContainer = document.getElementById('productSearchResults');
      
      let html = `<div class="p-3">
        <h6>${product.name || '未命名商品'} - 选择变体</h6>
        <div class="variation-list">
      `;
      
      variations.forEach(variation => {
        // 构建变体属性描述，处理属性值可能为option或value的情况
        let attributesDesc = '';
        if (variation.attributes && variation.attributes.length > 0) {
          const attributeValues = variation.attributes.map(attr => {
            // 处理属性值可能为option或value的情况
            const attrValue = attr.option || attr.value || '';
            const attrName = attr.name || '';
            return `${attrName}: ${attrValue}`;
          }).join(', ');
          attributesDesc = attributeValues;
        }
        
        html += `
          <div class="product-search-item" onclick="selectVariation(${JSON.stringify(product).replace(/"/g, '&quot;')}, ${JSON.stringify(variation).replace(/"/g, '&quot;')})">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <strong>${product.name || '未命名商品'}</strong>
                <div class="small text-muted">${attributesDesc || '默认变体'}</div>
                <div class="small">SKU: ${variation.sku || 'N/A'} | 价格: $${variation.price || '0.00'}</div>
              </div>
              <div class="text-primary">
                <i class="fas fa-plus-circle"></i>
              </div>
            </div>
          </div>
        `;
      });
      
      html += `
        </div>
        <div class="mt-2">
          <button class="btn btn-sm btn-secondary" onclick="closeVariationSelection()">取消</button>
        </div>
      </div>`;
      
      resultsContainer.innerHTML = html;
    }
    
    // 关闭变体选择界面
    function closeVariationSelection() {
      document.getElementById('productSearchResults').style.display = 'none';
      document.getElementById('searchProduct').value = '';
    }
    
    // 选择变体
    function selectVariation(product, variation) {
      // 隐藏搜索结果
      document.getElementById('productSearchResults').style.display = 'none';
      document.getElementById('searchProduct').value = '';
      
      // 商品名称保持原始名称，不添加属性信息
      const productName = product.name || '未命名商品';
      
      // 处理变体属性，确保属性值正确显示
      let processedAttributes = [];
      if (variation.attributes && variation.attributes.length > 0) {
        processedAttributes = variation.attributes.map(attr => {
          return {
            name: attr.name || '',
            value: attr.option || attr.value || ''
          };
        });
      }
      
      // 添加变体商品到列表
      addProductItem({
        id: variation.id || '',
        name: productName,  // 保持原始商品名称
        sku: variation.sku || '',
        price: parseFloat(variation.price) || 0,
        quantity: 1,
        total: parseFloat(variation.price) || 0,
        attributes: processedAttributes,
        parent_id: product.id || '', // 保存父商品ID
        is_variation: true // 标记为变体商品
      });
    }
    
    // 添加商品项
    function addProductItem(product) {
      const container = document.getElementById('productsContainer');
      const index = products.length;
      
      // 添加到商品数组
      products.push(product);
      
      // 确保商品名称不为undefined
      const productName = product.name || '新商品';
      
      // 创建商品项HTML，处理属性值可能为option或value的情况
      let attributesHtml = '';
      if (product.attributes && product.attributes.length > 0) {
        const attributeItems = product.attributes.map(attr => {
          // 处理属性值可能为option或value的情况
          const attrValue = attr.value || '';
          const attrName = attr.name || '';
          return `
            <div class="col-md-6 mb-2">
              <div class="input-group">
                <span class="input-group-text">${attrName}</span>
                <input type="text" class="form-control" value="${attrValue}" readonly>
              </div>
            </div>
          `;
        }).join('');
        
        attributesHtml = `
          <div class="mb-3">
            <label class="form-label">商品属性</label>
            <div class="row">
              ${attributeItems}
            </div>
          </div>
        `;
      }
      
      // 创建商品项HTML
      const productItem = document.createElement('div');
      productItem.className = 'product-item';
      productItem.innerHTML = `
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="mb-0">${productName}</h6>
          <span class="remove-product" onclick="removeProduct(${index})">
            <i class="fas fa-times-circle fa-lg"></i>
          </span>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">商品名称 *</label>
            <input type="text" class="form-control product-name" data-index="${index}" value="${productName}" required>
          </div>
          <div class="col-md-3 mb-3">
            <label class="form-label">SKU</label>
            <input type="text" class="form-control product-sku" data-index="${index}" value="${product.sku || ''}">
          </div>
          <div class="col-md-3 mb-3">
            <label class="form-label">商品ID</label>
            <input type="text" class="form-control product-id" data-index="${index}" value="${product.id || ''}" readonly>
          </div>
        </div>
        
        <div class="row">
          <div class="col-md-3 mb-3">
            <label class="form-label">单价 *</label>
            <div class="input-group">
              <span class="input-group-text">$</span>
              <input type="number" class="form-control product-price" data-index="${index}" value="${product.price || 0}" step="0.01" min="0" required>
            </div>
          </div>
          <div class="col-md-3 mb-3">
            <label class="form-label">数量 *</label>
            <input type="number" class="form-control product-quantity" data-index="${index}" value="${product.quantity || 1}" min="1" required>
          </div>
          <div class="col-md-3 mb-3">
            <label class="form-label">小计 *</label>
            <div class="input-group">
              <span class="input-group-text">$</span>
              <input type="number" class="form-control product-total" data-index="${index}" value="${product.total || 0}" step="0.01" min="0" readonly>
            </div>
          </div>
        </div>
        
        ${attributesHtml}
      `;
      
      container.appendChild(productItem);
      
      // 绑定事件
      bindProductEvents(index);
      
      // 更新总计
      updateTotals();
    }
    
    // 绑定商品事件
    function bindProductEvents(index) {
      // 绑定价格和数量变化事件
      const priceInput = document.querySelector(`.product-price[data-index="${index}"]`);
      const quantityInput = document.querySelector(`.product-quantity[data-index="${index}"]`);
      const totalInput = document.querySelector(`.product-total[data-index="${index}"]`);
      const nameInput = document.querySelector(`.product-name[data-index="${index}"]`);
      
      // 价格变化时更新小计
      priceInput.addEventListener('input', function() {
        updateProductTotal(index);
        updateTotals();
      });
      
      // 数量变化时更新小计
      quantityInput.addEventListener('input', function() {
        updateProductTotal(index);
        updateTotals();
      });
      
      // 名称变化时更新标题
      nameInput.addEventListener('input', function() {
        const productItem = this.closest('.product-item');
        const title = productItem.querySelector('h6');
        title.textContent = this.value || '新商品';
      });
    }
    
    // 更新商品小计
    function updateProductTotal(index) {
      const price = parseFloat(document.querySelector(`.product-price[data-index="${index}"]`).value) || 0;
      const quantity = parseInt(document.querySelector(`.product-quantity[data-index="${index}"]`).value) || 0;
      const total = price * quantity;
      
      document.querySelector(`.product-total[data-index="${index}"]`).value = total.toFixed(2);
      
      // 更新商品数组
      if (products[index]) {
        products[index].price = price;
        products[index].quantity = quantity;
        products[index].total = total;
      }
      
      // 更新订单总额
      updateOrderTotal();
    }
    
    // 更新总计
    function updateTotals() {
      // 更新商品数量
      const itemCount = products.reduce((sum, product) => sum + (parseInt(product.quantity) || 0), 0);
      document.getElementById('item_count').value = itemCount;
      
      // 更新订单总额
      updateOrderTotal();
    }
    
    // 移除商品
    function removeProduct(index) {
      if (confirm('确定要移除这个商品吗？')) {
        // 从数组中移除
        products.splice(index, 1);
        
        // 重新渲染商品列表
        const container = document.getElementById('productsContainer');
        container.innerHTML = '';
        
        products.forEach((product, i) => {
          addProductItem(product);
        });
        
        // 更新总计
        updateTotals();
      }
    }
    
    // 表单提交前处理
    document.getElementById('addOrderForm').addEventListener('submit', function(e) {
      // 将商品数据转换为JSON并填入隐藏字段
      document.getElementById('item_details').value = JSON.stringify(products);
    });
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 初始化时根据默认选中的来源站点设置货币符号
      const sourceSelect = document.getElementById('source');
      if (sourceSelect.value) {
        const currencySymbol = document.getElementById('currencySymbol');
        if (siteCurrencies[sourceSelect.value]) {
          currencySymbol.textContent = siteCurrencies[sourceSelect.value];
        }
      }
    });
  </script>
</body>
</html>